// -*- coding: utf-8 -*-
// @Time : 2024/9/1 下午10:15
// @Author : 423A35C7
// @Site : 
// @File : audio.js
// @Software: WebStorm

import {entities_store} from "@/global_store";

export async function play_audio(url, audio_name) {
    if (entities_store.sounds.num_at_once[audio_name] >= entities_store.sounds.max_num_at_once[audio_name]) return;
    entities_store.sounds.num_at_once[audio_name]++;
    if (!(audio_name in entities_store.sounds.audio_buffer)) {
        let res = await fetch(url);
        let {value, } = await res.body.getReader().read();
        // if (!done) {
        //     return;
        // }
        entities_store.sounds.audio_buffer[audio_name] = await entities_store.sounds.audio_context.decodeAudioData(value.buffer);
        entities_store.sounds.num_at_once[audio_name] = 0;
    }
    // if (source) source.stop();
    let source = entities_store.sounds.audio_context.createBufferSource();
    source.buffer = entities_store.sounds.audio_buffer[audio_name];
    source.connect(entities_store.sounds.audio_context.destination);
    source.addEventListener("ended", () => {
        entities_store.sounds.num_at_once[audio_name]--;
    })
    source.start();
}